const app = getApp()

export function post(postData, callbackFun, isShowLodding, original) {
  var that = this;
  postData = !postData ? {} : postData;
  var data = {
    app_sn: app.globalData.API_SN,
    extend: app.globalData.API_EXTEND,
  };
  if (app.globalData.userToken) {
    postData.user_token = app.globalData.userToken;
  }
  data = Object.assign(data, postData);

  (isShowLodding === true) && wx.showLoading({});
  wx.request({
    url: app.globalData.API_URL,
    data: data,
    success: function (res) {
      (isShowLodding === true) && wx.hideLoading();
      var data = res.data;
      if (data.return_code != 'success') { //直接提示错误信息
        console.log('error:', postData);
        console.log('error1:', data);
        wx.showModal({
          // title: '错误提示',
          content: data.data_value,
          showCancel: false,
          success: function (res) {
            if (res.confirm) {

            }
          }
        })
      } else { //返回data_array数据
        if (callbackFun && typeof callbackFun == 'function') {
          if (original === true){
             callbackFun(data);
          }else{
            var len = (typeof data.data_array == 'object') ? Object.keys(data.data_array).length : data.data_array.length;
            var retArr = (len > 0) ? data.data_array : data.data_value;
            callbackFun(retArr);
          }
        }
      }
    }
  })
}

//收集FROMID
export function formIdCollect(formId, num) {
  var that = this;
  var num = !num ? 1 : num;
  //this.cache('cacheFormIds', null);
  var time = Date.parse(new Date());
  var maxLength = 2; //收集够5个就提交 
  var formIds = this.cache('cacheFormIds');

  var fromIdArr = formIds ? formIds : [];
  for (var i = 0; i < num; i++) {
    fromIdArr.push({ time: time, formId: formId })
  }
  //console.log(fromIdArr)
  //that.alert('收集数量:'+fromIdArr.length);
  if (fromIdArr.length >= maxLength) {
    var data = { method: 'stxia.sapp.fromid', form_ids: formIds, user_token: app.globalData.userToken };
    that.post(data, function (ret) {
      that.cache('cacheFormIds', null);
    })
  } else {
    this.cache('cacheFormIds', fromIdArr)
  }
}

//上传文件... 
export function uploadFile(filePath, formData, callbackFun, isShowLodding) {
  var formData = formData ? Object.assign(formData, { 'method': 'stxia.file.upload' }) : { 'method': 'stxia.file.upload' };
  (isShowLodding === true) && wx.showLoading({});
  wx.uploadFile({
    url: app.globalData.API_URL,
    filePath: filePath,
    name: 'file',
    header: {
      'content-type': 'multipart/form-data'
    }, // 设置请求的 header
    formData: formData, // HTTP 请求中其他额外的 form data
    success: function (res) {
      (isShowLodding === true) && wx.hideLoading();
      var data = JSON.parse(res.data); //返回的是字符串，坑货...
      if (data.return_code != 'success') { //直接提示错误信息
        wx.showModal({
          // title: '错误提示',
          content: '上传图片失败',
          showCancel: false,
          success: function (res) {
            if (res.confirm) {

            }
          }
        })
      } else { //返回data_array数据
        if (callbackFun && typeof callbackFun == 'function') {
          callbackFun(data.data_value);
        }
      }
    }
  })
}

//上传文件到OSS... 
export function uploadFileOss(filePath, callbackFun, isShowLodding) {
  const uploadImage = require("./weixinFileToaliyun/uploadAliyun.js");
  var config = app.globalData.OSS_CONFIG;
  if (!config.uploadHost || !config.AccessKeySecret || !config.OSSAccessKeyId) {
    main.alert('没有配置项'); return false;
  }
  var dir = config['dir'] ? config['dir'] : 'images/';

  (isShowLodding === true) && wx.showLoading({});
  uploadImage({ filePath: filePath, dir: dir }, config, function (res) {
    console.log('return_pic:',res);
    if (!res) {
      wx.showModal({
        // title: '错误提示',
        content: '上传图片失败',
        showCancel: false,
        success: function (res) {
          if (res.confirm) {
          }
        }
      })
    } else {
      if (callbackFun && typeof callbackFun == 'function') {
          callbackFun(res);
      }
    }
  })

}


//缓存操作  
export function cache(key, value, expire) {
  if (value === null) {
    //console.log("删除缓存:" + key);
    // 删除缓存
    wx.removeStorage({
      key: key,
      success: function (res) {
        return false;
      }
    })
    wx.removeStorage({ key: 'EXPIRE_TIME_' + key })
  } else if (!value || value == undefined) {
    // console.log('获取缓存:' + key);
    var expireCache = wx.getStorageSync('EXPIRE_TIME_' + key);
    //console.log('缓存时间:' + expireCache)
    if (expireCache && expireCache < Date.parse(new Date())) {
      //console.log('过期处理了..');
      wx.removeStorage({ key: key })
      wx.removeStorage({ key: 'EXPIRE_TIME_' + key })
      return '';
    }

    // 读取缓存
    try {
      var value = wx.getStorageSync(key)
      if (value) {
        return value;
      }
    } catch (e) {
      // Do something when catch error
    }
  } else {
    //console.log("设置缓存:" + key);
    //设置缓存
    // var val = (typeof value == 'object') ? JSON.stringify(value) : value;
    if (expire && expire > 0) {
      var expireTime = Date.parse(new Date()) + 1000 * expire;
      wx.setStorageSync('EXPIRE_TIME_' + key, expireTime); //设置缓存过期时间..
    }

    wx.setStorage({
      key: key,
      data: value,
      success: function (res) {
        return true;
      },
      fail: function (res) {
        return false;
      }
    })
  }
}

//提示弹窗消息
export function alert(message,callback) {
  wx.showModal({
    // title: '错误提示',
    content: message,
    showCancel: false,
    success: function (res) {
      if (res.confirm) {
        callback && callback();
      }
    }
  })
}

//confirm
export function confirm(message, callback) {
  wx.showModal({
    title: '确认提示',
    content: message,
    showCancel: true,
    success: function (res) {
      if (res.confirm) {
        callback && callback();
      }
    }
  })
}

//提示消息
export function msg(msg, msgType, callback, time) {
  var time = time ? time : 1500;
  var msgType = msgType ? msgType : 'success';
  wx.showToast({
    title: msg,
    icon: msgType,
    duration: time,
    success: function (res) {
      setTimeout(function () {
        callback && callback();
      }, time)
    }
  })
}




//获取最后一个数组的ID。
export function getLastId(arr, field) {
  if (arr.length <= 0) return 0;
  return arr[arr.length - 1][field];
}


//取出二位数组的健值
export function getArrKeyVal(arr, key, val) {
  if (arr.length <= 0) return {};
  var obj = {};
  for (var i = 0; i < arr.length; i++) {
    obj[arr[i][key]] = arr[i][val];

  }
  return obj;
}

/**
 * 获取用户信息
 * userToken 用户的TOKEN
 * callback  异步回调
 * refresh   是否强制刷新,不刷新的话能是取得缓存数据
 */
export function userInfo(userToken, callback, refresh) {
  //console.log(userToken);
  var that = this;
  if (refresh !== true) {
    var userInfo = this.cache('userInfo');
    if (userInfo) {
      callback && callback(userInfo);
      return true;
    }
  }
  this.post({ method: 'ttl.user.get', user_token: userToken }, function (data) {
    that.cache('userInfo', data);
    callback && callback(data);
  })
}

/**
 * 获取配置信息
 * userToken 用户的TOKEN
 * callback  异步回调
 * refresh   是否强制刷新,不刷新的话能是取得缓存数据
 */
export function getConf(callback, refresh) {
  //this.cache('sysConf', null);
  var that = this;
  if (refresh !== true) {
    var conf = this.cache('sysConf');
    if (conf) {
      callback && callback(conf);
      return true;
    }
  }
  this.post({ method: 'laoqin.get.conf' }, function (data) {
    that.cache('sysConf', data, 86400); //设置的30秒过期
    callback && callback(data);
  })
}

/** 
 * 时间戳转化为年 月 日 时 分 秒 
 * time: 传入时间戳
 * format：返回格式，支持自定义，但参数必须与formateArr里保持一致 
*/
export function formatTime(time, format) {
  var formateArr = ['Y', 'm', 'd', 'h', 'i', 's'];
  var returnArr = [];

  var date = new Date(time * 1000);
  returnArr.push(date.getFullYear());
  returnArr.push(this.formatNumber(date.getMonth() + 1));
  returnArr.push(this.formatNumber(date.getDate()));

  returnArr.push(this.formatNumber(date.getHours()));
  returnArr.push(this.formatNumber(date.getMinutes()));
  returnArr.push(this.formatNumber(date.getSeconds()));

  for (var i in returnArr) {
    format = format.replace(formateArr[i], returnArr[i]);
  }
  return format;
}
//数据转化  
export function formatNumber(n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}  
